from DrissionPage import Chromium
from DrissionPage.common import Settings
from datetime import datetime
from dateutil.relativedelta import relativedelta
import time
import re
import traceback
import pyperclip

# 检索关键词
verify_pattern = r'(?=.*鸿蒙)(?=.*next)'
file_path = "D:\workspace\crawler\data\抖音.txt"
url_file_path = "D:\workspace\crawler\data\抖音-URL.txt"

def write_append(file_path, texts):
    with open(file_path, 'a', encoding='utf-8') as f:
        if not texts:
            return
        f.writelines(texts)

def get_dateline_seconds():
    # 获取当前时间（带时区可替换为 datetime.now(timezone.utc)）
    now = datetime.now()
    # 计算 6 个月前的时间
    six_months_ago = now - relativedelta(months=6)
    # 转换为时间戳（秒）
    timestamp = int(six_months_ago.timestamp())
    return timestamp

def get_card_url(card):
    try:
        aweme_id = card['aweme_info']['aweme_id']
        return f'https://www.douyin.com/video/{aweme_id}'
    except Exception:
        traceback.print_exc()
        print('卡片数据：\n')
        print(card + '\n')
    return None

def get_card_create_time(card):
    try:
        return card['aweme_info']['create_time']
    except Exception:
        traceback.print_exc()
    return None

def collect_url(main_tab, search_key):
    main_tab.listen.start('https://www.douyin.com/aweme/v1/web/general/search/single')
    main_tab.get(f'https://www.douyin.com/root/search/{search_key}?type=general')
    error_count = 0
    while error_count < 10:
        try:
            body = main_tab.listen.wait(timeout=10).response.body # 等待并获取一个数据包
            if not body or body['status_code'] != 0:
                continue
            card_list = body['data']
            if not card_list:
                print('没有卡片更多数据了，退出循环...\n')
                break
            for card in card_list:
                card_url = get_card_url(card)
                if card_url:
                    write_append(url_file_path, [card_url, '\n'])
            error_count = 0
            main_tab.wait.load_start()
        except Exception:
            error_count = error_count + 1
            traceback.print_exc()
            print(f'循环获取卡片数据异常，尝试次数：{error_count}')
        finally:
            try:
                main_tab.wait.ele_displayed('@tag()=html').scroll.to_bottom()
            except Exception:
                print('滚动到卡片列表底部异常\n')

def run():
    Settings.set_language('zh_cn')  # 设置为中文
    # 启动或接管浏览器，并创建标签页对象
    main_tab = Chromium().latest_tab
    # 这之后出现的弹窗都会自动确认
    main_tab.browser.set.auto_handle_alert()

    collect_url(main_tab, '鸿蒙Next动画')
    collect_url(main_tab, '鸿蒙Next动效')
    collect_url(main_tab, '鸿蒙Next')

run()